/**
 * @import libs
 */
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { storeToRefs } from 'pinia'

/**
 * @import pinia stores
 */

// pinia -> useShoppingStaticMessStore
import { useShoppingStaticMessStore } from '@/stores/shopping/shoppingStaticMess.js'

export const useShoppingPageStore = defineStore('shoppingPage', () => {

    /**
     * @param goodsList 商品列表
     * @param currentGoodsList 当前商品列表
     * @param goodTypeList 商品类型列表
     */
    let { goodsList, currentGoodsList, goodTypeList } = storeToRefs(useShoppingStaticMessStore())

    /**
     * 搜索框值
     */
    let searchValue = ref('')

    /**
     * 筛选商品列表
     * @param {Array<String>} keyWords 搜索关键字组
     */
    const filterGoodsList = (keyWords) => {
        
        // 如果为空，则显示所有商品
        if (keyWords.length == 1 && keyWords[0] == '') {
            currentGoodsList.value = goodsList.value
            return
        }

        currentGoodsList.value = goodsList.value.filter(item => {
            return keyWords.some((keyWord) => {

                //去除前后空格
                keyWord = keyWord.trim()
                return item.name.includes(keyWord)
            })
        })
    }

    /**
     * 购物输入框输入
     * @param {String} value
     * @returns {void}
     */
    const onSearchInput = (value) => {
        
        //判断value是否为undefined
        if (value === undefined) {
            console.error('value is undefined')
            return
        }

        // 去除前后空格并放在数组中
        const values = [value.trim()]
        filterGoodsList(values)
    }

    /**
     * 商品类型栏目点击
     * @param {Number} id 商品类型id
     */
    const goodsTypeBarClick = (id) => {
        
        // 判断id是否为undefined
        if (id === undefined) {
            console.error('id is undefined')
            return
        }
        
        // 判断id类型是否为Number
        if (typeof id !== 'number') {
            console.error('id is not number')
            return
        }
        
        //通过id筛选获取对象
        let item = goodTypeList.value.filter(item => item.id == id)
        
        let keyWords=item[0].keyWords
        
        // 将keyWords转为数组
        keyWords=Array.from(keyWords)

        //通过keyWords筛选商品列表
        filterGoodsList(keyWords)
    }

    return {
        searchValue,
        onSearchInput,
        goodsTypeBarClick
    }
})